package action

import java.text.SimpleDateFormat
import java.util.Date
import java.util.concurrent.{Executors, Future, LinkedBlockingQueue}

import Utils.ProbUtil
import beans.UserBean
import org.apache.commons.lang3.RandomUtils

/**
  * Created by hunter.coder 涛哥  
  * 2019/2/11 20:12
  * 交流qq:657270652
  * Version: 1.0
  * 更多学习资料：https://blog.csdn.net/coderblack/
  * Description:
  **/
object Mocker {

  def main(args: Array[String]): Unit = {
    if(args.size<1){
      println("""
        Usage:
        |user_num : 模拟的用户数量,默认1万
        |submit_delayrange_low:用户批次提交间隔的最小延迟时间,默认10秒
        |submit_delayrange_high: 用户批次提交间隔的最大延迟时间,默认40秒
        """)
    }
    var user_num = 100000   // 模拟用户数
    var submit_delayrange_low:Long = 1000  // 用户批次提交间隔的最小延迟时间 1秒
    var submit_delayrange_high:Long = 4000  // 用户批次提交间隔的最大延迟时间 4秒

    if(args.size == 1){
      user_num = args(0).toInt
    }
    if(args.size == 3) {
      user_num = args(0).toInt
      submit_delayrange_low =  args(1).toLong  //
      submit_delayrange_high = args(2).toLong //
    }

    val uq: LinkedBlockingQueue[UserBean] = new LinkedBlockingQueue[UserBean]()
    val service = Executors.newCachedThreadPool()

    val start = System.currentTimeMillis()
    val userNumb = 10000
    println(s"----构造${userNumb}用户开始------")
    for (i <- 0 to userNumb) {
      val u = ProbUtil.userBean
      uq.put(u)
    }
    val end = System.currentTimeMillis()
    println(s"----构造${userNumb}用户结束-----耗时： "+ (end-start)/1000)


    val size = uq.size()
    println("----用户队列总大小------: " + size)

    val sdf = new SimpleDateFormat("HH")
    while (true) {
      val date = new Date().getTime
      val hourStr = sdf.format(date)
      val hour = Integer.parseInt(hourStr)
      var factor = 0.0
      hour match {
        case v if (20 < v && v <= 23) => factor = 0.8
        case v if (14 < v && v <= 20) => factor = 0.6
        case v if (10 < v && v <= 14) => factor = 0.5
        case _ => factor = 0.2
      }
      val online = RandomUtils.nextInt((1000 * factor).asInstanceOf[Int], (5000 * factor).asInstanceOf[Int])

      println(s"${hour}点,当前在线人数： $online")
      for (i <- 0 to online) {
        // 取出一个用户准备去操作
        val u = uq.take()
        // 为了放置用户挨个轮着上的状况，设置一定概率直接返回队列重取
        if (ProbUtil.probilityDo(60)) {
          uq.add(u)
        } else {
          service.submit(new ActionController(u, uq, 1.5))
        }

      }

      // 提交完一批用户，设置一定时间的暂缓，
      Thread.sleep(RandomUtils.nextLong(submit_delayrange_low,submit_delayrange_high))

    }

  }

}
